/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs.web;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gtugs.domain.Chapter;
import org.gtugs.domain.Event;
import org.gtugs.service.ChapterManager;
import org.gtugs.service.EventManager;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * @author mangini@gmail.com (Renato Mangini)
 */
public class EventsController implements Controller {

  private ChapterManager chapterManager;
  private EventManager eventManager;

  @SuppressWarnings("unchecked")
  public ModelAndView handleRequest(HttpServletRequest request,
      HttpServletResponse response) throws ServletException {

    List<Event> events = null;

    String chapterStr = request.getParameter("chapter");
    if (chapterStr != null) {
      try {
        Long chapterLong = Long.valueOf(chapterStr);
        events= eventManager.getEventsForChapter(chapterLong, request.getParameter("all")==null);

      } catch (NumberFormatException nfe) {
        // TODO: Add proper error logging.
      }
    } else {
      events = eventManager.getEvents(request.getParameter("all")==null);
    }
    
    JSONArray list = null;

    if (events != null) {
      
      // get chapters for the events that will be listed:
      HashSet<Long> ids=new HashSet<Long>();
      for (Event event : events) {
        ids.add(event.getChapterId());
      }
      
      HashMap<Long, Chapter> chaptersMap=new HashMap<Long, Chapter>();
      List<Chapter> chapters=chapterManager.getChapters(ids);
      for (Chapter chapter: chapters) {
        chaptersMap.put(chapter.getId(), chapter);
      }
      
      list = new JSONArray();
      for (Event event : events) {
        JSONObject map = new JSONObject();
        map.put("chapterId", event.getChapterId());
        Chapter chapter=chaptersMap.get(event.getChapterId());
        if (chapter!=null) {
          map.put("chapterName", chapter.getName());
          map.put("chapterUrl", "http://www.gtugs.org/chapter.jsp?id=" +
              chapter.getId());
          map.put("chapterWebsite", chapter.getWebsite());
          map.put("chapterStatus", chapter.getStatus());
        }
        map.put("id", event.getId());
        map.put("name", event.getName());
        map.put("timeZone", event.getTimeZone());
        map.put("startDate", event.getStartDate());
        map.put("endDate", event.getEndDate());
        map.put("city", event.getCity());
        map.put("state", event.getState());
        map.put("country", event.getCountry());
        map.put("latitude", event.getLatitude());
        map.put("longitude", event.getLongitude());
        map.put("url", event.getUrl());
        map.put("themes", event.getTopics());
        list.add(map);
      }
    }

    return new ModelAndView(new JsonView(), "events", list);
  }

  public void setEventManager(EventManager eventManager) {
    this.eventManager = eventManager;
  }
  public void setChapterManager(ChapterManager chapterManager) {
    this.chapterManager = chapterManager;
  }
}
